from pathlib import Path
import os

from git import Repo
from dotenv import load_dotenv

from ops import get_commit_info


def get_changed_files(commit):
    """Get list of changed file names in a commit, excluding initial commits.

    Args:
        commit: GitPython Commit object

    Returns:
        list[str]: List of changed file names
    """
    if len(commit.parents) == 0:
        return []

    changed_files = set()

    # Compare with all parents to get complete change set
    for parent in commit.parents:
        for diff in commit.diff(parent):
            # Add old and new paths in case of renames
            if diff.a_path:
                changed_files.add(diff.a_path)
            if diff.b_path and diff.b_path != diff.a_path:
                changed_files.add(diff.b_path)

    return sorted(list(changed_files))


def build(repo: Repo, hash: str):
    repo.git.reset("--hard", hash)
    repo.git.checkout(hash)

    repo.git.clean("-f", "-d", "-x")
    repo.git.clean("-f", "-d", "-x")
    repo.git.clean("-f", "-d", "-x")

    print(f"COMMIT_ID={hash} task benchmark_hap_hermes benchmark_hap_jsvm")
    exit_code = os.system(f"COMMIT_ID={hash} task benchmark_hap_hermes benchmark_hap_jsvm")
    assert exit_code == 0, f"Error: {exit_code}"


if __name__ == "__main__":
    SCRIPT_DIR = Path(__file__).parent
    load_dotenv(SCRIPT_DIR / ".env")
    RNOH_DIR = Path(os.getenv("RNOH_DIR"))

    repo = Repo(RNOH_DIR)

    build(repo, "b03635b06e7436d6f16ce7118759d3036faef27f")
    exit()

    repo.remotes.origin.fetch()
    repo.git.reset("--hard", "origin/master")
    repo.git.checkout("master")
    repo.git.reset("--hard", "origin/master")

    would_clean = repo.git.clean("-n", "-d")
    if len(would_clean) != 0:
        print(would_clean)
        if input("Input y to continue: ").lower() != "y":
            exit(0)
        repo.git.clean("-f", "-d")

    # start = False
    for commit in list(repo.iter_commits("HEAD", max_count=1000)):
        info = get_commit_info(repo, commit)

        # if commit.hexsha == "325a3319c642880e007aa0cffcebe8b32cc351ef":
        #     start = True
        # if not start:
        #     continue
        # if commit.hexsha == "27c07839e3dfc9aa96147d8a68e9e69aa41bbed2":
        #     break
        # if not info["is_merge"]:
        #     continue

        # prefix = "5.1.0."
        # tags = info["tags"]
        # if len(tags) != 1 or tags[0][: len(prefix)] != prefix:
        #     continue
        # print(info["hash"], info["tags"])

        # if len(info["tags"]) == 0:
        #     continue

        # if info["is_merge"] or len(info["tags"]) != 0:
        # if len(info["tags"]) != 0:

        files = get_changed_files(commit)
        if all(f.endswith(".md") for f in files):
            continue

        build(repo, commit.hexsha)
